<!--
 * @Author: luthor luthor-li@qq.com
 * @Date: 2024-02-21 19:38:25
 * @LastEditors: fisher luthor-li@qq.com
 * @LastEditTime: 2024-11-01 12:19:19
 * @FilePath: \allfront\src\modules\cloud\projManager\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="moduleMain">
    <div class="operate">
      <div class="upload">
        <div class="uploadMask">
          <span>点击上传ue附件（zip格式）</span>
          <input
            class="uploadInput"
            ref="fileInput"
            type="file"
            @change="handleFileChange"
          />
        </div>

        <div v-if="uploading" class="progress">
          <span>上传中</span>
          <!-- 上传中...进度：{{ progress.toFixed(0) }}% -->
          <el-progress
            :percentage="parseInt(progress)"
            :text-inside="true"
            :stroke-width="20"
            striped
          />
        </div>
        <div v-if="!mergeProgress.status" class="progress">
          <span>合并中</span>
          <el-progress
            :percentage="parseInt(mergeProgress.data)"
            :text-inside="true"
            :stroke-width="20"
            striped
          />
          <!-- 合并中。。。进度{{ mergeProgress.data }}% -->
        </div>
        <!-- <div v-if="!unzipProgress.status" class="progress">
          <span>解压中</span>
          <el-progress
            :percentage="parseInt(unzipProgress.data)"
            :text-inside="true"
            :stroke-width="20"
            striped
          />
        </div> -->
      </div>
      <el-button type="primary" @click="publish" style="margin-left: auto">
        主控机文件列表
      </el-button>
      <el-button type="success" @click="syncfile"> 集群同步文件 </el-button>
      <!-- <el-button type="danger" @click="deleteUefile">删除工程</el-button> -->
    </div>
    <div class="table">
      <div class="table_menu">
        <div class="table_menu_title">集群列表</div>
        <div
          v-for="item in clusterData"
          :key="item.id"
          @click="checkCluster(item.id)"
        >
          <el-button v-if="item.id !== currentCluster">
            {{ item.host }}
          </el-button>
          <el-button type="primary" v-if="item.id == currentCluster">
            {{ item.host }}
          </el-button>
        </div>
      </div>
      <div class="table_content">
        <el-table
          stripe
          :data="tableData"
          style="width: 100%; height: calc(100% - 60px)"
        >
          <el-table-column property="name" label="工程名称" width="120" />
          <el-table-column
            property="originalPath"
            label="原始文件地址"
            width="300"
          />
          <el-table-column property="path" label="工程文件地址" width="300" />
          <el-table-column
            property="downloadStatus"
            label="下载状态"
            width="120"
          >
            <template #default="scope">
              <el-button type="success" v-if="scope.row.downloadStatus">
                已下载
              </el-button>
              <el-button type="info" v-if="!scope.row.downloadStatus">
                未下载
              </el-button>
            </template>
          </el-table-column>
          <el-table-column property="deployStatus" label="部署状态" width="120">
            <template #default="scope">
              <el-button type="success" v-if="scope.row.deployStatus">
                已部署
              </el-button>
              <el-button type="info" v-if="!scope.row.deployStatus">
                未部署
              </el-button>
            </template>
          </el-table-column>
          <el-table-column
            property="createdAt"
            label="部署时间"
            show-overflow-tooltip
          >
            <template #default="scope">
              {{ dayjs(scope.row.createdAt).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="table_page"
          :current-page="pageNo"
          :page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <BigfileDialog
      ref="bigfileDialog"
      :bigfileData="bigfileData"
    ></BigfileDialog>
  </div>
</template>
<script setup>
import { reactive, ref, onMounted } from 'vue';
import useBigfileUpload from '@/hooks/useBigfileUpload';
import BigfileDialog from './bigfileDialog.vue';
import dayjs from 'dayjs';
import { useAxios } from '@/hooks/useAxios';
// import { useDeleteConfirmation } from '@/hooks/useDeleteConfirm';
// const { deleteData } = useDeleteConfirmation();
const { uploading, progress, uploadFileChunks, mergeProgress } =
  useBigfileUpload();
const { post, get } = useAxios();
const handleFileChange = event => {
  const file = event.target.files[0];
  if (file) {
    uploadFileChunks(file, 'uefile');
  }
};
/**
 * @description: 监听合并结果，调用处理ue文件接口
 * @return {*}
 */
// watch(combineRes, () => {
//   console.log('combineRes', combineRes);
//   const fileName = combineRes.data.originalFilename.split('.')[0];
//   const data = {
//     fileName: fileName || 'ueproject',
//     filePath: combineRes.data.path,
//   };
//   // handleUefile(data);
// });
// input dom获取，用于清空input文件
const fileInput = ref(null);
/**
 * @description: 处理ue上传压缩包，解压至对应目录
 * @param {*} data
 * @return {*}
 */
// const unzipProgress = reactive({
//   status: true,
// });
// const unzipTimer = ref(null);
// const handleUefile = data => {
//   ElNotification({
//     title: 'Info',
//     message: '正在处理ue文件...',
//     type: 'info',
//   });
//   fileInput.value.value = '';
//   post('/ueserver/unzipUe', data).then(res => {
//     console.log('unzip res', res);
//     const taskId = res.data;
//     unzipTimer.value = setInterval(async () => {
//       const progressResponse = await get(
//         `/ueserver/getUnzipUeProgress/${taskId}`,
//       );
//       unzipProgress.status = progressResponse.data.status;
//       unzipProgress.data = progressResponse.data.data;
//       if (progressResponse.data.status) {
//         clearInterval(unzipTimer.value);
//         unzipTimer.value = null;
//         pageSize.value = 10;
//         pageNo.value = 1;
//         getData();
//       }
//     }, 2000);
//   });
// };

let tableData = reactive([]);
let total = ref(0);
let pageNo = ref(1);
let pageSize = ref(10);
// let search = ref('');
onMounted(() => {
  getCluster();
  // getData();
});
const getData = () => {
  const data = {
    pageNo: pageNo.value,
    pageSize: pageSize.value,
    clusterId: currentCluster.value,
  };
  post('/uefile/getsyncFile', data).then(res => {
    if (res?.status) {
      // 先清空，后赋值,表格数据赋值
      tableData.length = 0;
      tableData.push(...res.data);
      console.log('tableData', tableData);
      total.value = res.page.total;
    }
  });
};
// let selectData = reactive([]);
// const handleSelectionChange = val => {
//   if (val.length) {
//     selectData.length = 0;
//     val.forEach(item => {
//       selectData.push(item._id);
//     });
//   }
// };
const handleSizeChange = val => {
  pageSize.value = val;
  getData();
};
const handleCurrentChange = val => {
  pageNo.value = val;
  getData();
};

// const deleteUefile = () => {
//   deleteData(selectData, data => {
//     return post('/ueserver/deleteUefiles', {
//       ids: data,
//     }).then(() => {
//       getData();
//     });
//   });
// };

// onBeforeUnmount(() => {
//   if (unzipTimer.value) clearInterval(unzipTimer.value);
//   unzipTimer.value = null;
// });

const bigfileData = reactive([]);
const bigfileDialog = ref();
const publish = () => {
  get('/upload/getUefiles').then(res => {
    if (res) {
      bigfileData.length = 0;
      bigfileData.push(...res.data);
      bigfileDialog.value.dialogFormVisible = true;
    }
  });
};
// const handlePublish = val => {
//   const fileName = val.name.split('.')[0];
//   const data = {
//     fileName: fileName || 'ueproject',
//     filePath: val.filePath,
//   };
//   handleUefile(data);
// };

// 获取cluster数据
const clusterData = reactive([]);
const currentCluster = ref('');
const getCluster = () => {
  post('/cluster/getCluster', {
    pageNo: 1,
    pageSize: -1,
  }).then(res => {
    if (res?.status) {
      // 先清空，后赋值,表格数据赋值
      clusterData.length = 0;
      clusterData.push(...res.data);
      // 当存在数据,则默认选择第一个数据展示
      if (clusterData.length) {
        currentCluster.value = clusterData[0].id;
        getData();
      }
    }
  });
};
const checkCluster = id => {
  if (id) {
    currentCluster.value = id;
    getData();
  }
};

const syncfile = () => {
  // 检查是否正在同步文件
  get('/uefile/checkSyncFileStatus').then(res => {
    console.log('checkSyncFileStatusres == ', res);
    if (res.data.length) {
      ElNotification({
        title: 'Info',
        message: '请等待上一轮同步文件完成！',
        type: 'info',
      });
      return;
    } else {
      get('/uefile/clustersyncFile').then(res => {
        console.log('clustersyncFile', res);
        getData();
      });
    }
  });
};
</script>

<style scoped>
.moduleMain {
  padding: 20px;
  box-sizing: border-box;
}
.operate {
  width: 100%;
  height: 80px;
  display: flex;
  align-items: center;
}
.upload {
  display: flex;
  align-items: center;
  gap: 15px;
}
.uploadMask {
  width: 300px;
  height: 60px;
  border: 1px dashed #333;
  border-radius: 5px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  position: relative;
  font-size: 14px;
  color: #333;
}
.uploadInput {
  width: 100%;
  height: 100%;
  opacity: 0;
  position: absolute;
  top: 0;
  left: 0;
}
.progress {
  width: 350px;
  display: flex;
  gap: 10px;
}
.el-progress,
.el-progress--line {
  flex: 1;
}
.table {
  height: calc(100% - 80px);
  display: flex;
}
/* :deep(.el-table) {
  height: calc(100% -60px);
} */
.table_page {
  height: 60px;
  justify-content: flex-end;
}
.table_menu {
  width: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}
.table_menu_title {
  margin-top: 20px;
  font-weight: bold;
}
.table_content {
  flex: 1;
}
</style>
